package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer {
    private DatagramSocket datagramSocket;
    public UDPServer(int port) throws SocketException {
        datagramSocket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动：");
        while(true) {
            //创建一个数据报用于接收数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[65536], 65536);
            //接收数据
            datagramSocket.receive(requestPacket);
            //解析请求
            String result = new String(requestPacket.getData(), 0, requestPacket.getLength());
            System.out.println("接收到请求：" + requestPacket.getAddress() + ": " + result);
            //构造响应
            String response = requestPacket.getAddress() + ": " + result;
            //创建一个响应数据报
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getAddress(), requestPacket.getPort());
            //发送响应
            datagramSocket.send(responsePacket);
            System.out.println("返回响应：" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPServer server = new UDPServer(8090);
        server.start();
    }
}
